﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.Models;
using Code.BLL;
using Code.Commen;
using QianBuo.Lottery.Web.Models.Account;
using System.Text.RegularExpressions;

namespace QianBuo.Lottery.Web.Controllers
{
    public class AccountController : BaseController
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return RedirectToAction("Report");
        }

        public ActionResult Report(ReportModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Page < 1)
                    model.Page = 1;
                if (model.PageSize < 1)
                    model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(20);

                var UM = new UserManage();
                if (!string.IsNullOrEmpty(model.Serch.LoginName))
                {
                    var user = UM.Select(s => s.Any(p => p.LoginName == model.Serch.LoginName && p.Commands.Contains(LoginUserID.ToString())));
                    if (!user)
                        ModelState.AddModelError("Error", "不存在该用户！");
                }
                else
                    model.Serch.LoginName = LoginUser.LoginName;

                var accounts = UM.GetUserAccountReport(model.Serch, LoginUserID);
                accounts = accounts.Where(p => p.LoginName == model.Serch.LoginName);
                model.Account = UM.Select<Account, Account>(s => s.FirstOrDefault(p => p.Users.LoginName == model.Serch.LoginName));
                model.MimSerchEndTime = (UM.Select<UserAccountDetail, UserAccountDetail>(s => s.OrderBy(p => p.AddTime).FirstOrDefault()) ?? new UserAccountDetail { AddTime = DateTime.Now.Date }).AddTime;
                model.SumCount = accounts.Count();
                if (model.SumCount > 0)
                {
                    model.SumReport = accounts.GroupBy(p => 1).Select(p => new AccountReportModel
                    {
                        SumAddMoney = p.Sum(pp => pp.SumAddMoney),
                        SumPlayMoney = p.Sum(pp => pp.SumPlayMoney),
                        SumTackMoney = p.Sum(pp => pp.SumTackMoney),
                        SumBackMoney = p.Sum(pp => pp.SumBackMoney),
                        SumBackMoney_Child = p.Sum(pp => pp.SumBackMoney_Child),
                        SumWinMoney = p.Sum(pp => pp.SumWinMoney),
                        SumWinMoney_Child = p.Sum(pp => pp.SumWinMoney_Child)
                    }).First();
                    model.Reports = accounts.OrderByDescending(p => p.Year).OrderByDescending(p => p.Month).OrderByDescending(p => p.Day)
                        .Select(p => new AccountReportModel
                        {
                            Year = p.Year,
                            Month = p.Month,
                            Day = p.Day,
                            SumAddMoney = p.SumAddMoney,
                            SumPlayMoney = p.SumPlayMoney,
                            SumTackMoney = p.SumTackMoney,
                            SumBackMoney = p.SumBackMoney,
                            SumBackMoney_Child = p.SumBackMoney_Child,
                            SumWinMoney = p.SumWinMoney,
                            SumWinMoney_Child = p.SumWinMoney_Child
                        }).Skip(model.PageSize * (model.Page - 1)).Take(model.PageSize).ToArray();
                    model.Reports.Each(p => { p.Date = new DateTime(p.Year, p.Month, p.Day); });
                }
            }
            return View(model);
        }

        public ActionResult Detail(DetailModel model)
        {
            if (model == null)
                model = new DetailModel();
            if (model.Serch == null)
                model.Serch = new UserManage.UserAccountDetailSerch();
            model.Types = (Enum.GetValues(typeof(UserAccountDetailType)) as UserAccountDetailType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.Types.Insert(0, new SelectListItem { Text = "所有明细", Value = string.Empty });
            if (ModelState.IsValid)
            {
                if (model.PageSize <= 0)
                    model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(20);
                if (!model.Page.HasValue)
                    model.Page = 1;

                UserManage UM = new UserManage();
                if (string.IsNullOrEmpty(model.Serch.LoginName))
                    model.Serch.LoginName = base.LoginUser.LoginName;
                var report = UM.GetUserAccountDetail(model.Serch, base.LoginUserID);

                var reg = new Regex(@"^\w{1,}:[-0-9]{1,}期", RegexOptions.Compiled);
                var issubmoney=(!model.Serch.Type.HasValue && !model.Serch.MaxMoney.HasValue && !model.Serch.MinMoney.HasValue);
                double money = base.LoginUser.Balance;
                if (issubmoney)
                {
                    var m = UM.GetUserAccountDetail(new UserManage.UserAccountDetailSerch { LoginName = model.Serch.LoginName, StartTime = (model.Serch.EndTime ?? DateTime.Now).Date.AddDays(1) }, base.LoginUserID).Where(p => p.Memo==null || !p.Memo.Contains("(已付)")).Sum(p => (double?)(p.InMoney ?? 0) + (-p.OutMoney ?? 0)) ?? 0;
                    m += report.OrderBy("AddTime DESC,Type").Take(model.PageSize * (model.Page.Value - 1)).Where(p => p.Memo == null || !p.Memo.Contains("(已付)")).Sum(p => (double?)(p.InMoney ?? 0) + (-p.OutMoney ?? 0)) ?? 0;
                    money = Math.Round(money - m, 4);
                }
                model.SumCount = report.Count();
                if (model.SumCount > 0)
                {
                    model.SumDetail = report.GroupBy(p => 1).Select(p => new AccountDetail { InMoney = p.Sum(pp => pp.InMoney), OutMoney = p.Sum(pp => pp.OutMoney) }).FirstOrDefault() ?? new AccountDetail();
                    model.Details = report.OrderBy("AddTime DESC,Type").Skip(model.PageSize * (model.Page.Value - 1)).Take(model.PageSize)
                        .Select(p => new AccountDetail { ID = p.ID, AddTime = p.AddTime, Memo = p.Memo, State = p.State, InMoney = p.InMoney, OutMoney = p.OutMoney, Type = (UserAccountDetailType)p.Type }).ToList();
                    model.Details.Each(p =>
                    {
                        if (issubmoney)
                        {
                            p.Money = money;
                            if (string.IsNullOrEmpty(p.Memo) || !p.Memo.Contains("(已付)"))
                                money = money + (-p.InMoney ?? 0) + (p.OutMoney ?? 0);
                        }
                        int? state; int tp;
                        state = int.TryParse(p.State, out tp) ? tp as int? : null;
                        if ((p.Type == UserAccountDetailType.QuashScheme || p.Type == UserAccountDetailType.Other) && p.ID != null && (p.Info = p.ID.Split('&').Select(pp => { var nv = pp.Split(':'); return new { N = nv[0], V = nv[1] }; }).ToDictionary(pp => pp.N, pp => pp.V)).Count > 0)
                            p.ID = p.Info.ContainsKey("RefID") ? p.Info["RefID"] : null;

                        if (p.Type == UserAccountDetailType.AddMoney) p.StateText = ((AddMoneyType)state).GetName();
                        if (p.Type == UserAccountDetailType.BackMoney_Child || p.Type == UserAccountDetailType.WinMoney_Child || p.Type == UserAccountDetailType.Play ||
                            p.Type == UserAccountDetailType.WinMoney || p.Type == UserAccountDetailType.QuashScheme || p.Type == UserAccountDetailType.BackMoney ||
                            (p.Type == UserAccountDetailType.Other && state == (short)OtherMoneyDetailType.BackTimeOutScheme))
                        {
                            if (reg.IsMatch(p.Memo ?? string.Empty))
                            {
                                int i1 = p.Memo.IndexOf(":");
                                int i2 = p.Memo.IndexOf("期");
                                var str = p.Memo.Substring(0, i1);
                                LotteryType l = (LotteryType)int.Parse(str);
                                str = p.Memo.Substring(i1 + 1, i2 - i1 - 1);
                                var str1 = Issue.PastIssueName(l, str);
                                p.Memo = string.Format("{0}:{1}{2}", l.GetName(), str1, p.Memo.Substring(i2));
                            }
                        }
                        if (p.Type == UserAccountDetailType.Other && state.HasValue) { p.StateText = ((OtherMoneyDetailType)state).GetName(); }
                        if (p.Type == UserAccountDetailType.ChaseTask && state.HasValue) { p.StateText = ((ChaseTaskState)state).GetName(); p.Memo = ((LotteryType)int.Parse(p.Memo)).GetName() + "追号任务"; }
                        if (p.Type == UserAccountDetailType.Freez && state.HasValue) { p.StateText = ((FreezeMoneyDetailState)state).GetName(); p.Memo = ((FreezeCause)int.Parse(p.Memo)).GetName(); }
                    });
                    if (issubmoney && model.Page * model.PageSize >= model.SumCount)
                        model.Details.Add(new Web.Models.Account.AccountDetail { AddTime = model.Serch.StartTime, LoginName = model.Serch.LoginName, Money = money, Memo = "结转之前的余额" });
                }
                else if (issubmoney)
                {
                    model.Details = new List<Web.Models.Account.AccountDetail>();
                    model.SumDetail = new Web.Models.Account.AccountDetail();
                    model.Details.Add(new Web.Models.Account.AccountDetail { AddTime = model.Serch.StartTime, LoginName = model.Serch.LoginName, Money = money, Memo = "结转之前的余额" });
                }
            }

            return View(model);
        }


    }
}
